var base = $("base").attr("ul");
var subTableId = $('base').attr('subTableId');
var relationId = $('base').attr('relationId');


var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
    width: 2000,
    height: 1500,
    model: graph,
    gridSize: 1,
    snapLinks: true,
    linkPinning: false,
    defaultLink: new joint.dia.Link({
        // router: { name: 'manhattan' },
        connector: { name: 'rounded' },
        attrs: {
            '.connection': {
                stroke: '#20C1DD',
                'stroke-width': 2,
                'stroke-dasharray': '5 2',
                pointerEvents: 'none',
            },
            '.marker-target': {
                fill: '#20C1DD',
                stroke: '#fff',
                d: 'M 10 0 L 0 5 L 10 10 z'
            }
        },
    }),
});
//paper背景
var bgimage = '';
paper.drawBackground({
    image : bgimage
});

//控制纸张
var paperScroller = new joint.ui.PaperScroller({
    paper: paper,
    autoResizePaper: true,
    padding: 50,
    cursor: 'grab'
});
// 移动纸张
paper.on('blank:pointerdown', paperScroller.startPanning);
$('#paper').append(paperScroller.render().el);
paperScroller.center();    //移动到页面的中间


var commandManager = new joint.dia.CommandManager({
    graph: graph
});
var toolbar = new joint.ui.Toolbar({   //头部控制模块
    groups: {
        'undo-redo': { index: 1 },
        'clear': { index: 2 },
        'export': { index: 3 },
        'print': { index: 4 },
        'layout': { index: 5 },
        'order': { index: 6 },
        'zoom': { index: 7 },
        'fullscreen': { index: 8 },
        'grid': { index: 9 },
        'snapline': { index: 10 }
    },
    tools: [
        {
            type: 'button',
            name: 'undo',
            group: 'undo-redo',
            attrs: {
                button: {
                    'id':'btn-undo',
                    'data-tooltip': '撤销',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'redo',
            group: 'undo-redo',
            attrs: {
                button: {
                    'id':'btn-redo',
                    'data-tooltip': '返回',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'clear',
            group: 'clear',
            attrs: {
                button: {
                    id: 'btn-clear',
                    'data-tooltip': '清除',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'svg',
            group: 'export',
            text: 'Export SVG',
            attrs: {
                button: {
                    id: 'btn-svg',
                    'data-tooltip': '导出SVG',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'png',
            group: 'export',
            text: 'Export PNG',
            attrs: {
                button: {
                    id: 'btn-png',
                    'data-tooltip': '导出PNG',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'button',
            name: 'print',
            group: 'print',
            attrs: {
                button: {
                    id: 'btn-print',
                    'data-tooltip': '打印',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
/*        {
            type: 'button',
            group: 'layout',
            name: 'layout',
            attrs: {
                button: {
                    id: 'btn-layout',
                    'data-tooltip': '自动布局',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },*/
        {
            type: 'zoom-to-fit',
            name: 'zoom-to-fit',
            group: 'zoom',
            attrs: {
                button: {
                    'data-tooltip': '自适应缩放',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },
        {
            type: 'label',
            name: 'zoom-slider-label',
            group: 'zoom',
            text: 'Zoom:'
        },
        {
            type: 'zoom-slider',
            name: 'zoom-slider',
            group: 'zoom'
        },

        {
            type: 'toggle',
            name: 'toggle',
            group: 'last',
            value:true
        },

    /*    {
            type: 'button',
            name: 'search',
            group: 'last',
            text: '搜索',
            attrs: {
                button: {
                    id: 'btn-search',
                    'data-tooltip': '搜索',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        },*/
        {
            type: 'button',
            name: 'refresh',
            group: 'last',
            text: '刷新',
            attrs: {
                button: {
                    id: 'btn-refresh',
                    'data-tooltip': '刷新',
                    'data-tooltip-position': 'top',
                    'data-tooltip-position-selector': '.toolbar-container'
                }
            }
        }
    ],
    references: {
        paperScroller: paperScroller,
        commandManager: commandManager
    }
});

$('#app').prepend(toolbar.render().el);

//中英文切换
toolbar.on('toggle:change', function(value, event) {

    $.each(graph.getElements(),function(i,v){
        var cell = v;
        var view = paper.findViewByModel(v);
        var currentColumn = view.$el.find(".columnName");

        //如果是中文
        if(value === true){

            cell.attributes.attrs.isEnglish = false; //是中文
            view.$el.find("tspan").text(cell.attributes.attrs.objectChname);
            $.each(currentColumn, function (i, v) {
                var columnchname = $(this).attr("data-columnchname");

                $(this).text(columnchname);

            })
        }else {

            cell.attributes.attrs.isEnglish = true; //是英文
            view.$el.find("tspan").text(cell.attributes.attrs.tableName);

            $.each(currentColumn, function (i, v) {
                var columnchname = $(this).attr("data-columnname");

                $(this).text(columnchname);

            })
        }

        cell.attributes.attrs.div.html = view.$el.find('.content').html();
    })
    var promptMsg = "";
    value=== true?promptMsg="已切换为中文":promptMsg = "已切换为英文";
    layer.msg(promptMsg,{time:1500})
});

//halo组件
var halo;
//点击元素
paper.on('cell:pointerclick',function(cellView){
    console.log(cellView);
    $('.body').removeClass('eleHighlight');
    cellView.$el.find('.body').addClass('eleHighlight');

    halo = new joint.ui.Halo({theme: 'modern', cellView: cellView});
    //元素只连接元素
    halo.on('action:link:add', function(link) {
        if (!link.get('source').id || !link.get('target').id) {
            link.remove();
        }
    });
    halo.removeHandle('clone');
    halo.removeHandle('fork');
    halo.removeHandle('unlink');
    halo.removeHandle('remove');
    halo.removeHandle('rotate');
    halo.render();

    var sourceLink = graph.getConnectedLinks(cellView.model,{inbound : false,outbound:true });
    var targetLink = graph.getConnectedLinks(cellView.model,{inbound : true,outbound:false });
    $.each(sourceLink,function(i,v){

        var sourceLinkView =  paper.findViewByModel(v.id);
        sourceLinkView.$el.find('.connection').addClass('eleToSourceLink');
        sourceLinkView.$el.find('.marker-target').addClass('eleToSourceLinkT');
    })

    $.each(targetLink,function(i,v){

        var targetLinkView =  paper.findViewByModel(v.id);
        targetLinkView.$el.find('.connection').addClass('eleToTargetLink');
        targetLinkView.$el.find('.marker-target').addClass('eleToTargetLinkT');
    })




    if($('base').attr('rawType')=='fm'){
        console.log(cellView);
        halo.removeHandle('link');

    }
});


//元素间的对齐线
var snaplines = new joint.ui.Snaplines({ paper: paper });
snaplines.startListening();

//鹰眼开始
var nav = new joint.ui.Navigator({
    paperScroller: paperScroller,
    width: 133,
    height: 100,
    padding: 5,
    model: graph,
    gridSize: 1,
});
nav.$el.appendTo('#myholder-small');
nav.render();
//小图结束

//tooltip模块
new joint.ui.Tooltip({
    target: '[data-tooltip]',
    rootTarget: document.body,
    direction: 'auto',
    padding: 15,
});


$("#app").on('click','.tool-options',function(){    //点击编辑关系线
    var id=	$(this).parents(".joint-cell").attr("model-id");
    var link = graph.getCell(id);
    console.log(link)
    layer.open({
        title : '添加逻辑外键关系',
        type: 2,
        content: [requestUrl+'/page/modelModify/addFKRelate?objId='+link.attributes.source.id+'&referObjId='+link.attributes.target.id+'&lineId='+link.attributes.id],
        area:  ['800px', '400px'],
        maxmin: true
    });
});

//双击元素
paper.on('cell:pointerdblclick', function(cellView) {
    if($(cellView.el).hasClass("joint-type-bpmn")){  //bpmn元素
        //console.log(cellView.model.attributes.participants[0]);
        layer.open({
            type: 2,
            title:cellView.model.attributes.participants[0],
            content: [requestUrl+'/page/dataObj/index?tableId='+ cellView.model.id],
            area: ['900px', '500px'],
            maxmin: true,
            cancel:function(index,layero){
             //   console.log(currentData);
                $.ajax({
                    url: requestUrl+'/rest/webpage/render/dataObj?objId='+cellView.model.id,
                    type: 'GET',
                    dataType: 'json',
                    data: {},
                    success: function (data) {
                        console.log(data);

                        $(cellView.el).find('tspan').text(data.objectChname ? data.objectChname : data.tableName); //修改表的标题

                        var fieldsArr = [];
                        $.each(data.columns, function (i, v) {

                            var columnFeature = "[";
                            if (v.pk){
                                columnFeature = columnFeature + "PK,";
                            }
                            if (v.fk){
                                columnFeature = columnFeature + "FK,";
                            }
                            if (v.nk){
                                columnFeature = columnFeature + "NK,";
                            }

                            if (columnFeature.charAt(columnFeature.length-1) == ','){
                                columnFeature = columnFeature.substring(0, columnFeature.length -1) + "]";
                            }
                            else {
                                columnFeature = "";
                            }

                            var pfields = '<tr><td class="fieldsTd">'+(v.columnChname ? v.columnChname.replace(/\s/g, '') : v.columnName)+'</td><td class="fieldsTd">'+v.dataTypeFullText+'</td><td>'+columnFeature+'</td></tr>';
                            fieldsArr.push(pfields);
                        });

                        var tableStr = '<table>'+fieldsArr.join('') +'</table>';
                        $(cellView.el).find('.content').html(tableStr);   //修改view中表的content
                        var ins = new joint.ui.Inspector({
                            cellView:cellView.model,
                        });
                        ins.options.cellView.attributes.attrs.div.html = tableStr;  //修改model中表的content
                    },
                    error: function (data) {
                        console.log(data)
                    }
                });

            }
        });
    }
});

paper.on('blank:pointerclick',function(){  //单击页面时移除所有的高亮
    $('.body').removeClass('eleHighlight');
    $('.connection').removeClass('linkHighlight eleToSourceLink eleToTargetLink');
    $('.marker-target').removeClass('linkTargetHighlight eleToSourceLinkT eleToTargetLinkT')
});

